{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a91acd66",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\oscar'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2629c086",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.chdir('C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3b5b3996",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the directory where you want to save the best model\n",
    "save_dir = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\bestmodelsMAML'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ebbc501b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.preprocessing import image\n",
    "import keras.backend as K\n",
    "import numpy as np\n",
    "import cv2\n",
    "import sys\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6a86bfcc-9978-41d6-a2b9-3180f60282b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.models import load_model\n",
    "\n",
    "model_path = r\"C:\\Users\\oscar\\Documents\\experimentos\\2025_Four_carnivores_MAML\\bestmodels\\bestmodelsMAML\\resnet50.keras\"\n",
    "model1 = load_model(model_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "30b81d8f-5eeb-43bd-8ff6-4ddea79139cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_path = r\"C:\\Users\\oscar\\Documents\\experimentos\\2025_Four_carnivores_MAML\\bestmodels\\bestmodelsMAML\\resnet152.keras\"\n",
    "model2 = load_model(model_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9353ca18-7905-460f-89fc-3f61c8a73734",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_path = r\"C:\\Users\\oscar\\Documents\\experimentos\\2025_Four_carnivores_MAML\\bestmodels\\bestmodelsMAML\\xception.keras\"\n",
    "model3 = load_model(model_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "66c43701-52ef-4c36-aa6c-3546399a7905",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_path = r\"C:\\Users\\oscar\\Documents\\experimentos\\2025_Four_carnivores_MAML\\bestmodels\\bestmodelsMAML\\densenet.keras\"\n",
    "model4 = load_model(model_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e56ac6c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "members=[model1,model2,model3,model4]#actualizar!!!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b532a313",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0fc42f9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "64d3cab5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#loads image to be classified. Activate libraries\n",
    "\n",
    "from tensorflow.keras.preprocessing import image\n",
    "import keras.backend as K\n",
    "import numpy as np\n",
    "import cv2\n",
    "import sys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d77561e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6c903eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#ESTO ES POR SI QUIERES HACER ENSEMBLE ANALISIS CON LOS TRES MODELOS JUNTOS Y CON LAS IMÁGENES PRE-PROCESADAS CON LOS TRES MODELOS. ES UN PROCESO PONDERADO. LLAMAME Y TYE EXPLICO QUE ES. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "cd4392c3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1/1 [==============================] - 0s 65ms/step\n",
      "1/1 [==============================] - 0s 182ms/step\n",
      "1/1 [==============================] - 0s 127ms/step\n",
      "1/1 [==============================] - 0s 143ms/step\n",
      "File Name: B+OH7+30+1.bmp\n",
      "Predicted Label: leopard\n",
      "Predicted Probabilities: [0.    0.001 0.998 0.001]\n",
      "Label from Filename: B+OH7+30+1\n",
      "\n",
      "1/1 [==============================] - 0s 77ms/step\n",
      "1/1 [==============================] - 0s 165ms/step\n",
      "1/1 [==============================] - 0s 97ms/step\n",
      "1/1 [==============================] - 0s 124ms/step\n",
      "File Name: C+OH7+15+2B.bmp\n",
      "Predicted Label: leopard\n",
      "Predicted Probabilities: [0.016 0.018 0.933 0.033]\n",
      "Label from Filename: C+OH7+15+2B\n",
      "\n",
      "1/1 [==============================] - 0s 80ms/step\n",
      "1/1 [==============================] - 0s 150ms/step\n",
      "1/1 [==============================] - 0s 114ms/step\n",
      "1/1 [==============================] - 0s 133ms/step\n",
      "File Name: OH65+45+1.bmp\n",
      "Predicted Label: leopard\n",
      "Predicted Probabilities: [0.229 0.215 0.533 0.023]\n",
      "Label from Filename: OH65+45+1\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from keras.preprocessing import image\n",
    "from keras.applications.resnet50 import preprocess_input as preprocess_resnet50\n",
    "from keras.applications.resnet import preprocess_input as preprocess_resnet152\n",
    "from keras.applications.xception import preprocess_input as preprocess_xception\n",
    "from keras.applications.efficientnet import preprocess_input as preprocess_efficientnet\n",
    "from keras.applications.densenet import preprocess_input as preprocess_densenet\n",
    "import numpy as np\n",
    "\n",
    "# Define the accuracies of the models\n",
    "accuracies = [85, 82.56, 85, 84.6]  # Accuracy of each model (update with your actual model accuracies)\n",
    "\n",
    "# Find the maximum accuracy\n",
    "max_accuracy = max(accuracies)\n",
    "\n",
    "# Calculate the weights\n",
    "weights = [(accuracy / max_accuracy) for accuracy in accuracies]\n",
    "\n",
    "# Path to the folder containing images\n",
    "folder_path = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\oh7bis'  # Directory where the images are stored\n",
    "\n",
    "# List all files in the folder\n",
    "image_files = os.listdir(folder_path)\n",
    "\n",
    "# Define class labels (modify according to your model)\n",
    "class_labels = {0: \"crocodile\", 1: \"hyena\", 2: \"leopard\", 3: \"lion\"}  # Example class names\n",
    "\n",
    "# Iterate over each image file\n",
    "for file_name in image_files:\n",
    "    # Load the image\n",
    "    img_path = os.path.join(folder_path, file_name)\n",
    "    img = image.load_img(img_path, target_size=(299, 299))  # Use 299x299 for Xception and EfficientNet V2L\n",
    "\n",
    "    # Preprocess the image for each model based on size\n",
    "    img_resnet50 = image.load_img(img_path, target_size=(224, 224))  # 224x224 for ResNet50 and DenseNet\n",
    "    img_resnet50 = image.img_to_array(img_resnet50)\n",
    "    img_resnet50 = np.expand_dims(img_resnet50, axis=0)\n",
    "    img_resnet50 = preprocess_resnet50(img_resnet50)\n",
    "\n",
    "    img_resnet152 = image.load_img(img_path, target_size=(224, 224))  # 224x224 for ResNet152\n",
    "    img_resnet152 = image.img_to_array(img_resnet152)\n",
    "    img_resnet152 = np.expand_dims(img_resnet152, axis=0)\n",
    "    img_resnet152 = preprocess_resnet152(img_resnet152)\n",
    "\n",
    "    img_xception = image.load_img(img_path, target_size=(299, 299))  # 299x299 for Xception\n",
    "    img_xception = image.img_to_array(img_xception)\n",
    "    img_xception = np.expand_dims(img_xception, axis=0)\n",
    "    img_xception = preprocess_xception(img_xception)\n",
    "\n",
    "    #img_efficientnet = image.load_img(img_path, target_size=(299, 299))  # 299x299 for EfficientNet V2L\n",
    "    #img_efficientnet = image.img_to_array(img_efficientnet)\n",
    "    #img_efficientnet = np.expand_dims(img_efficientnet, axis=0)\n",
    "    #img_efficientnet = preprocess_efficientnet(img_efficientnet)\n",
    "\n",
    "    img_densenet = image.load_img(img_path, target_size=(224, 224))  # 224x224 for DenseNet\n",
    "    img_densenet = image.img_to_array(img_densenet)\n",
    "    img_densenet = np.expand_dims(img_densenet, axis=0)\n",
    "    img_densenet = preprocess_densenet(img_densenet)\n",
    "\n",
    "    # Now, make predictions with each model in the ensemble\n",
    "    prediction_resnet50 = members[0].predict(img_resnet50)\n",
    "    prediction_resnet152 = members[1].predict(img_resnet152)\n",
    "    prediction_xception = members[2].predict(img_xception)\n",
    "    #prediction_efficientnet = members[3].predict(img_efficientnet)\n",
    "    prediction_densenet = members[3].predict(img_densenet)\n",
    "\n",
    "    # Combine predictions according to the ensemble strategy (average predictions)\n",
    "    final_prediction = (prediction_resnet50 + prediction_resnet152 + prediction_xception + prediction_densenet) / 4\n",
    "    \n",
    "    # Weighted prediction based on model accuracies\n",
    "    #weighted_prediction = (prediction_resnet50 * weights[0] + prediction_resnet152 * weights[1] + \n",
    "                           #prediction_xception * weights[2] + prediction_efficientnet * weights[3] + \n",
    "                           #prediction_densenet * weights[4])\n",
    "    weighted_prediction = (prediction_resnet50 * weights[0] + prediction_resnet152 * weights[1] + \n",
    "                           prediction_xception * weights[2] + \n",
    "                           prediction_densenet * weights[3])\n",
    "    # Normalize the weighted prediction\n",
    "    total_sum = weighted_prediction.sum()\n",
    "    normalized_prediction = weighted_prediction / total_sum\n",
    "\n",
    "    # Get predicted class index\n",
    "    predicted_class_index = np.argmax(normalized_prediction, axis=1)[0]\n",
    "\n",
    "    # Get the predicted label using the class_labels dictionary\n",
    "    predicted_label = class_labels.get(predicted_class_index, \"Unknown\")\n",
    "\n",
    "    # Round probabilities to 3 decimal places\n",
    "    rounded_probabilities = np.round(normalized_prediction[0], 3)\n",
    "\n",
    "    # Extract label from the image file name\n",
    "    label = file_name.split('.')[0]  # Assuming the label is the part of the file name before the first period\n",
    "    \n",
    "    # Print the final prediction, the corresponding label, and probabilities\n",
    "    print(f'File Name: {file_name}')\n",
    "    print(f'Predicted Label: {predicted_label}')\n",
    "    print(f'Predicted Probabilities: {rounded_probabilities}')\n",
    "    print(f'Label from Filename: {label}\\n')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26ba60b1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afdfb486",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export the DataFrame to a CSV file in the folder_path#results_df.to_csv(os.path.join(folder_path, 'predictionsResnet.csv'), index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
